package models

import (
	"time"

	"github.com/shopspring/decimal"
)

// UserMatrixAccount 用户矩阵账户模型
type UserMatrixAccount struct {
	BaseModel
	UserID                int64           `json:"user_id" gorm:"not null;index:idx_user_id"`
	MatrixAccount         string          `json:"matrix_account" gorm:"type:varchar(64);uniqueIndex:uk_matrix_account;not null"`
	MatrixAccountName     string          `json:"matrix_account_name" gorm:"type:varchar(64);not null"`
	PlatformType          string          `json:"platform_type" gorm:"type:varchar(32);default:photonpay;not null;index:idx_platform_type"`
	Status                string          `json:"status" gorm:"type:varchar(20);default:active;not null;index:idx_status"`
	TotalTransferAmount   decimal.Decimal `json:"totalTransferAmount" gorm:"type:decimal(20,2);default:0.00;not null"`
	ParentMatrixAccountID *int64          `json:"parent_matrix_account_id" gorm:"index:idx_parent_matrix_account_id"`
	User                  User            `gorm:"foreignKey:UserID" json:"user"`
	Balance               string          `json:"balance" gorm:"-"` // 非数据库字段，用于API响应
}

// TableName 获取表名
func (UserMatrixAccount) TableName() string {
	return "user_matrix_accounts"
}

// MasterAccount 主账号模型
type MasterAccount struct {
	BaseModel
	UserID         int64           `json:"user_id" gorm:"not null;uniqueIndex:uk_user_id"`
	AccountName    string          `json:"account_name" gorm:"type:varchar(50);not null"`
	AccountType    string          `json:"account_type" gorm:"type:varchar(20);default:enterprise;not null;index:idx_account_type"`
	Status         string          `json:"status" gorm:"type:varchar(20);default:active;not null;index:idx_status"`
	MaxSubAccounts int             `json:"max_sub_accounts" gorm:"type:int;default:10;not null"`
	Balance        decimal.Decimal `json:"balance" gorm:"type:decimal(20,2);default:0.00;not null"`
}

// TableName 获取表名
func (MasterAccount) TableName() string {
	return "master_accounts"
}

// IsActive 检查账号是否处于活跃状态
func (m *MasterAccount) IsActive() bool {
	return m.Status == "active"
}

// CanCreateSubAccount 检查是否可以创建子账号
func (m *MasterAccount) CanCreateSubAccount(currentCount int) bool {
	return m.IsActive() && currentCount < m.MaxSubAccounts
}

// ValidateAccountType 验证账号类型
func (m *MasterAccount) ValidateAccountType() bool {
	return m.AccountType == "enterprise" || m.AccountType == "individual"
}

// ValidateStatus 验证状态
func (m *MasterAccount) ValidateStatus() bool {
	validStatuses := map[string]bool{
		"active":   true,
		"inactive": true,
		"frozen":   true,
	}
	return validStatuses[m.Status]
}

// SubAccount 子账号模型
type SubAccount struct {
	ID              int64           `json:"id" gorm:"primaryKey"`
	MasterAccountID int64           `json:"master_account_id" gorm:"not null"`
	UserID          int64           `json:"user_id" gorm:"not null"`
	AccountName     string          `json:"account_name" gorm:"not null"`
	Role            string          `json:"role" gorm:"not null;default:operator"`
	Permissions     string          `json:"permissions" gorm:"type:json"`
	Status          string          `json:"status" gorm:"not null;default:active"`
	Balance         decimal.Decimal `json:"balance" gorm:"type:decimal(20,2);default:0.00;not null"`
	LastLoginTime   *time.Time      `json:"last_login_time" gorm:"default:null"`
	LastLoginIP     string          `json:"last_login_ip" gorm:"default:null"`
	CreatedAt       time.Time       `json:"created_at" gorm:"not null;default:CURRENT_TIMESTAMP"`
	UpdatedAt       time.Time       `json:"updated_at" gorm:"not null;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
}

// TableName 获取表名
func (SubAccount) TableName() string {
	return "sub_accounts"
}

// IsActive 检查子账号是否处于活跃状态
func (s *SubAccount) IsActive() bool {
	return s.Status == "active"
}

// ValidateRole 验证角色
func (s *SubAccount) ValidateRole() bool {
	validRoles := map[string]bool{
		"admin":    true,
		"operator": true,
		"viewer":   true,
	}
	return validRoles[s.Role]
}

// ValidateStatus 验证状态
func (s *SubAccount) ValidateStatus() bool {
	validStatuses := map[string]bool{
		"active":   true,
		"inactive": true,
		"frozen":   true,
	}
	return validStatuses[s.Status]
}

// MasterSubAccountFund 主账号子账号资金记录模型
type MasterSubAccountFund struct {
	BaseModel
	MasterAccountID int64           `json:"master_account_id" gorm:"not null;index:idx_master_account_id"`
	SubAccountID    int64           `json:"sub_account_id" gorm:"not null;index:idx_sub_account_id"`
	Amount          decimal.Decimal `json:"amount" gorm:"type:decimal(20,2);not null"`
	Type            string          `json:"type" gorm:"type:varchar(20);not null;index:idx_type"` // allocate/refund
	Remark          string          `json:"remark" gorm:"type:varchar(255)"`
}

// TableName 获取表名
func (MasterSubAccountFund) TableName() string {
	return "master_sub_account_funds"
}

// MasterSubAccountFundWithSubAccount 包含子账号信息的资金记录
type MasterSubAccountFundWithSubAccount struct {
	MasterSubAccountFund
	SubAccountName string `json:"sub_account_name" gorm:"column:sub_account_name"`
}

// SubAccountConsumeRecord 子账号消费记录模型
type SubAccountConsumeRecord struct {
	BaseModel
	SubAccountID int64           `json:"sub_account_id" gorm:"not null;index:idx_sub_account_id"`
	Amount       decimal.Decimal `json:"amount" gorm:"type:decimal(20,2);not null"`
	Type         string          `json:"type" gorm:"type:varchar(20);not null;index:idx_type"` // consume/refund
	Remark       string          `json:"remark" gorm:"type:varchar(255)"`
	OrderID      string          `json:"order_id" gorm:"type:varchar(64);index:idx_order_id"`
	Status       string          `json:"status" gorm:"type:varchar(20);not null;default:success;index:idx_status"`
}

// TableName 获取表名
func (SubAccountConsumeRecord) TableName() string {
	return "sub_account_consume_records"
}

// Agent 代理商模型
type Agent struct {
	BaseModel
	UserID         int64           `json:"user_id" gorm:"not null;uniqueIndex:uk_user_id"`
	ParentID       *int64          `json:"parent_id" gorm:"index:idx_parent_id"`
	ParentUserID   *int64          `json:"parent_user_id" gorm:"index:idx_parent_user_id"`
	Name           string          `json:"name" gorm:"type:varchar(50)"`
	Level          string          `json:"level" gorm:"type:varchar(1);default:1;not null;index:idx_level"`
	CommissionRate decimal.Decimal `json:"commission_rate" gorm:"type:decimal(10,2);default:0.00;not null"`
	Balance        decimal.Decimal `json:"balance" gorm:"type:decimal(10,2);default:0.00;not null"`
	InvitationCode string          `json:"invitation_code" gorm:"type:varchar(8);uniqueIndex:uk_invitation_code"`
	Status         string          `json:"status" gorm:"type:varchar(20);default:active;not null;index:idx_status"`
}

// TableName 获取表名
func (Agent) TableName() string {
	return "agents"
}

// SubAccountWithUser 包含用户信息的子账号模型
type SubAccountWithUser struct {
	SubAccount
	Username string `json:"username" gorm:"-"`
	Email    string `json:"email" gorm:"-"`
	Phone    string `json:"phone" gorm:"-"`
	Name     string `json:"name" gorm:"-"`
}
